package com.item.action;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.base.CoreConstants;
import com.base.action.CoreController;
import com.base.dao.model.BFile;
import com.base.service.BFileService;
import com.base.util.FileExportUtils;
import com.base.util.ImageUtils;
import com.base.util.MyOssClient;
import com.item.service.AdminService;

@Controller
public class WebRequestController extends CoreController {
	@Autowired
	private AdminService adminService;
	
	@Autowired
	BFileService fileService;
	private static final Logger logger = Logger.getLogger(WebRequestController.class);
	
	private static final String BUCKET_NAME = CoreConstants.BUCKET_NAME_FRAMEWORK;
	/**
	 * 进入主页
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/webindex")
	public String index(HttpSession session, ModelMap map) throws Exception {
		return "/web/index";
//		Object obj = session.getAttribute(LoginFilter.SESSION_USER_KEY);
//		if (obj != null) {
//			return "main";
//		}
//		return "login";
	}
	
	

	
	@RequestMapping("/bookdetail")
	public String bookdetail(String id) throws Exception {
		return "/web/detail";
	}
	
	@RequestMapping("/bookdtypes")
	public String bookdtypes(String id) throws Exception {
		return "/web/types";
	}
	
	@RequestMapping("/weblogin")
	public String weblogin(String id) throws Exception {
		return "/web/login";
	}
	
	@RequestMapping("/search")
	public String search(String id) throws Exception {
		return "/web/search";
	}
	
	@RequestMapping("/searchschool")
	public String searchschool(String id) throws Exception {
		return "/web/searchschool";
	}
	
	@RequestMapping("/webcarts")
	public String webcart(String id) throws Exception {
		return "/web/cart";
	}
	
	@RequestMapping("/weborders")
	public String weborder(String id) throws Exception {
		return "/web/order";
	}
	
	@RequestMapping("/webregist")
	public String webregist(String id) throws Exception {
		return "/web/regist";
	}
	
	@RequestMapping("/webaddorder")
	public String webaddorder(String id) throws Exception {
		return "/web/addorder";
	}
	
	@RequestMapping("/addinfo")
	public String addinfo(String id) throws Exception {
		return "/web/addinfo";
	}
	
	@RequestMapping("/findpfirst")
	public String findpfirst(String id) throws Exception {
		return "/web/findpassone";
	}
	
	@RequestMapping("/findpsec")
	public String findpsec(String id) throws Exception {
		return "/web/findpasssec";
	}
	
	@RequestMapping("/modifypass")
	public String modifypass() throws Exception {
		return "/web/modifypass";
	}
	
	
	@RequestMapping("/webaddorderall")
	public String webaddorderall(String id) throws Exception {
		return "/web/addorderall";
	}
	
	@RequestMapping("/news")
	public String news(String id) throws Exception {
		return "/web/news";
	}
	
	@RequestMapping("/downloadweb")
	@ResponseBody
	public String downloadFile(String id,HttpServletRequest request,HttpServletResponse resp,
			@RequestParam(value = "w", required = false) String w,
			@RequestParam(value = "h", required = false) String h,String type) throws Exception{
//		System.out.println(request.getHeader("If-Modified-Since"));
		String filepath = "";
		if(id!=null){
			BFile item = fileService.selectByPrimaryKey(id);
			if (item == null) {
				throw new Exception("文件不存在");
			} else {
				filepath = item.getFilePath();
//				File filepath = new File(CoreConstants.FILE_PATH + "/"+item.getFilePath());
//				if(item.getFileCreatetime().toGMTString().equals(request.getHeader("If-Modified-Since"))){
//					resp.setStatus(304);
//					return;
//				}
//				//byte[] fileData = MyOssClient.getObject(item.getFilePath(), BUCKET_NAME);
//				int width = 0, height = 0;
//				if (w != null && w.length() > 0) {
//					width = Integer.valueOf(w);
//				}
//				if (h != null && h.length() > 0) {
//					height = Integer.valueOf(h);
//				}
//				if (width != 0 && item.getFileMinitype().startsWith("image")) {
////					// 检查目录
////					File tempDirectory= new File(CoreConstants.FILE_PATH + "/temp/");
////					if (!tempDirectory.isDirectory()) {
////						tempDirectory.mkdirs();
////					}
////					String tf =CoreConstants.FILE_PATH + "/temp/" +  item.getFileMd5() +"_"+ width + "x" + height + ".png";
//					String tf =CoreConstants.FILE_PATH + "/temp/" +  item.getFileMd5() +"_"+ width + "x" + height + ".png";
//					File tempfile = new File(tf);
//					if (tempfile.exists()) {
//						filepath = tempfile;
//					} else {
//						if (height == 0) {
//							ImageUtils.Compress(filepath, tempfile, width);
//						} else {
//							ImageUtils.Compress(filepath, tempfile, width, height);
//						}
//						filepath = tempfile;
//					}
//					
				}
//				resp.setContentType(item.getFileMinitype() + "; charset=utf-8");
				if (StringUtils.isBlank(filepath)) {
					throw new Exception("文件没找到");
				}
//				FileExportUtils.download(resp, item.getFileName(), item.getFileMinitype(), filepath,type);
//			}
		}
		return filepath;
	}
	
	public static void download(HttpServletResponse response, String filename,
			String mimetype, byte[] data,String type, BFile item) throws Exception {
		OutputStream os = null;
		try {
			response.reset();
			response.setContentType(mimetype + "; charset=utf-8");
			response.addHeader("Last-Modified", item.getFileCreatetime().toGMTString());
			if ("inline".equals(type)) {
				response.setHeader("Content-Disposition","; filename=" + URLEncoder.encode(filename, "UTF-8"));
			}else{
				response.setHeader("Content-disposition","attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
			}
			if (data == null) {
				throw new Exception("图片文件没找到");
			}
			os = response.getOutputStream();
			response.setContentLength(data.length);
			os.write(data);
			os.flush();
		} finally {
			if (os != null) {
				os.close();
			}
		}
	}
}
